<?php

namespace app\index\controller;

use app\common\CommonResponse;
use app\index\validate\FileValidate;
use think\App;
use think\Controller;
use think\Request;

class File extends Base
{
    protected $fileModel;
    public function __construct(App $app = null)
    {
        parent::__construct($app);
        $this->fileModel=new \app\common\model\File();
    }

    /** 首页
     * @return mixed
     */
    public function list(){
        $files = $this->fileModel->paginate(10);
        $this->assign("files",$files);
        return $this->fetch();
    }


    public function addFile(Request $request){
        if($request->isPost()){
            $file=$request->post();
            $check=new FileValidate();
            if(!$check->check($file)){
                return $this->error($check->getError());
            }
            $file['user_id']=$this->user['id'];
            $file['create_time']=time();
            $save = $this->fileModel->save($file);
            if(!$save){
                return $this->error("科研成果添加失败");
            }
            return $this->success("科研成果添加成功","list");
        }
        return $this->fetch();

    }

    public function delFile(Request $request){
        if(!$request->post("id")){
            return CommonResponse::error("科研成果ID不能为空");
        }
        $fileId=$request->post("id");
        $deleteRes = $this->fileModel::get($fileId)->delete();
        if(!$deleteRes){
            return CommonResponse::error("科研成果删除失败");
        }
        return CommonResponse::success("科研成果删除成功");
    }

}
